<template>
    <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      ></Toolbar>
      <Editor
        :style="`height: ${height}; overflow-y: hidden;`"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      >
      </Editor>
    </div>
</template>

<script lang="ts" setup name="BaseEditor">
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import * as api from '@/api/index'
import { onBeforeUnmount, shallowRef, computed } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

type InsertFnType = (url: string, alt?: string, href?: string) => void
let props = withDefaults(defineProps<{
    modelValue: any
    // 模式 default --> 默认  simple--> 极简 
    mode?: string,
    // 富文本编辑器高度
    height?: string,
    placeholder?: string
  }>(), {
    modelValue: '',
    mode: 'default',
    height: '500px',
    placeholder: '请输入内容...'
  })
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

let emits = defineEmits(['update:modelValue'])

const valueHtml = computed({ // 重新定义
  get: () => props.modelValue,
  set: (value: string) => emits("update:modelValue", value),
})

// 图片拼接地址
let baseStr: string = import.meta.env.config_concat

const toolbarConfig = {}
const editorConfig = { 
    placeholder: props.placeholder,
    MENU_CONF: {
        uploadImage: {
            server: "/upload",
            async customUpload(file: File, insertFn: InsertFnType) {  // TS 语法
                let formData = new FormData()
                formData.append('file', file)
                formData.append('originMode', import.meta.env.config_mode)
                api.upload.blogUploadImage(formData).then((res) => {
                    let url = baseStr + res.body.url
                    insertFn(url, res.body.alt, url)
                })
            }
        }
    }
 }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

// 编辑器实例创建触发
const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
</script>    

<style lang="less" scoped>
</style>
